package com.example.eback.controller;

import com.example.eback.constans.ProjCode;
import com.example.eback.dao.FilesDAO;
import com.example.eback.dao.ProjectDAO;
import com.example.eback.entity.Proj.Project;
import com.example.eback.entity.Proj.user_proj;
import com.example.eback.dao.user_projDAO;
import com.example.eback.entity.UpLoadFile;
import com.example.eback.entity.User;
import com.example.eback.result.Result;
import com.example.eback.result.ResultCode;
import com.example.eback.result.ResultFactory;
import com.example.eback.service.FileService;
import com.example.eback.service.ProjService;
import com.example.eback.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Column;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class ProjController {
    @Autowired
    private UserUtils userUtils;
    @Autowired
    private ProjService projService;
    @Autowired
    private FilesDAO filesDAO;
    @Autowired
    private FileService fileService;

    /*
     *数据结构:permission: 身份 /如果为all则返回全部相关（权限不为not）
     */

    /**
     * 前端直接访问，然后去user_proj表里查询对应到该用户的pid以及permission
     * @param
     * @return
     */
    @GetMapping("/proj/my")
    public Result getMyProj(@RequestBody Map<String, Object> params){
        //获取当前用户的id
        User current_User=userUtils.getCurrentUser();
        int uid=current_User.getId();
        //获取权限
        String permission = (String) params.get("permission");

        //根据权限来查找，然后放入userProjList
        return ResultFactory.buildSuccessResult(projService.getProjByUidAndPermission(uid,permission));
    }

    /**
     * 创建历史记录，相当于创建的是一个UploadFile，其中初始只包含projectid，日期，简单的描述description
     * 传入的数据格式包括json格式的Date和Description
     * 返回给前端这个历史记录的id
     */

    @PostMapping("/createhistory")
    public Result CreateHistory(@RequestBody Map<String,Object> json) {
        try {
            Date date=(Date) json.get("Date");
            String description=(String) json.get("Description");
            if (date==null||description==null) {
                return ResultFactory.buildFailResult("信息请填完整");
            }
            //创建新的历史记录对象
            UpLoadFile currentUpLoadFile =new UpLoadFile();

            //设置参数
            currentUpLoadFile.setDate(date);
            currentUpLoadFile.setDesc_(description);
            //获取当前登陆的用户的id
            User current_User=userUtils.getCurrentUser();
            currentUpLoadFile.setUserId(current_User.getId());
            currentUpLoadFile.setStatus(0);
            currentUpLoadFile.setModelName(0);//0表示该文件还没有任何标签文件

            //保存
            fileService.saveFile(currentUpLoadFile);
            return ResultFactory.buildResult(ResultCode.SUCCESS,"创建成功",currentUpLoadFile.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultFactory.buildFailResult(e.getMessage());
        }
    }

    /**
     * 返回id为projectid值的所有项目
     * @param params
     * @return
     */
    //TODO:返回id为projId的项目全部关联信息 返回的数据结构注意实体类中@Transient
    @GetMapping("/proj/Info")
    public Result getMyJoinProj(@RequestBody Map<String, Object> params){
        int projId=(int)params.get("projectId");
        User current_User=userUtils.getCurrentUser();
        Project project = projService.findById(projId);
        if (project == null) {
            // handle the case where no project with the given id exists
            return ResultFactory.buildFailResult("没有根据这个id查找到项目");
        }
        List<UpLoadFile> upLoadFileList= filesDAO.findAllByPidAndUserId(projId,current_User.getId());
        project.setUpLoadFiles(upLoadFileList); // assuming this is the correct way to set the associated data
        return ResultFactory.buildSuccessResult(project);
    }

    /**
     * 创建新项目，包括的信息有姓名，身高，体重，年龄等信息，详情件project.class
     * @param params
     * @return
     */
    //TODO:新的Proj
    @PostMapping("/proj/creat")
    public Result creat(@RequestBody Map<String, Object> params){
        User current_User=userUtils.getCurrentUser();
        String name =(String) params.get("name");
        String description=(String) params.get("description");
        int userId=current_User.getId();
        double height=(double)params.get("height");
        double weight=(double)params.get("weight");
        String bloodType=(String)params.get("bloodType");
        int age=(int)params.get("age");
        String phone=(String)params.get("phone");
        Date birthday=(Date) params.get("birthday");
        String location=(String) params.get("location");

        Project project=new Project();
        project.setName(name);
        project.setDescription(description);
        project.setUserId(userId);
        project.setHeight(height);
        project.setWeight(weight);
        project.setBloodType(bloodType);
        project.setAge(age);
        project.setPhone(phone);
        project.setBirthday(birthday);
        project.setLocation(location);
        if(name==null){
            return ResultFactory.buildFailResult("名字为空");
        }
        else{
            projService.save(project);
            return ResultFactory.buildResult(ResultCode.SUCCESS,"保存成功",project);
        }
    }


    /**
     * 项目的删除
     * @param params
     * @return
     */
    //TODO:删除，注意权限判断
    @PutMapping("/proj/delete")
    public Result delete(@RequestBody Map<String, Object> params){
        int projId=(int)params.get("projectId");
        // 获取当前登录用户
        User currentUser = userUtils.getCurrentUser();
        if (currentUser == null) {
            return ResultFactory.buildFailResult("用户未登录");
        }
        // 删除项目
        ProjCode code = projService.delete(currentUser.getId(), projId);
        if (code.getCode()<0)
            return  ResultFactory.buildFailResult(code.getMsg());
        return  ResultFactory.buildSuccessResult(code.getMsg());

    }

    //TODO:新建一个Proj等级的协同富文本编辑器
    @PutMapping("/proj/createQuill/{projId}")
    public Result createQuill(@PathVariable int  projId){

        return ResultFactory.buildSuccessResult("");
    }


    //TODO:获取协同富文本编辑器
    @GetMapping("/api/proj/getQuill/{ProjId}")
    public Result getQuill(@PathVariable String ProjId){

        return ResultFactory.buildSuccessResult("");
    }

}
